package jlu.com.p2pdemo;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.NetworkInterface;
import java.net.SocketAddress;
import java.net.SocketException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Enumeration;

public class MainActivity extends AppCompatActivity {
    private static final String TAG = "MainActivity";
    private TextView tvMsg;
    private EditText txtIP, txtPort, txtEt, txtContent;
    private Button btnSend;
    private Handler handler;
    private String serverIP;
    private int port;
    private String message;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //找到控件

        tvMsg = (TextView) findViewById(R.id.tvMsg);
        txtIP = (EditText) findViewById(R.id.txtIP);
        txtPort = (EditText) findViewById(R.id.txtPort);
        txtContent = (EditText) findViewById(R.id.et_content);
        txtEt = (EditText) findViewById(R.id.et);
        btnSend = (Button) findViewById(R.id.btnSend);
        tvMsg.setText("本机IP：" + getHostIp());
        //更新UI
        handler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
                String prefix = "\n[" + format.format(new Date()) + "]";
                switch (msg.what) {
                    case 0:
                        txtEt.append(prefix + msg.obj.toString());
                        txtContent.setText("");
                        break;
                    case 1:
                        txtEt.append(prefix + msg.obj.toString());
                        break;
                }
            }
        };

        btnSend.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                serverIP = txtIP.getText().toString();
                port = Integer.parseInt(txtPort.getText().toString());
                message = txtContent.getText().toString();
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            SocketAddress target = new InetSocketAddress(serverIP, port);
                            DatagramSocket client = new DatagramSocket();
                            byte[] buffer = message.getBytes();
                            DatagramPacket sendPacket = new DatagramPacket(buffer, 0, buffer.length, target);
                            Message.obtain(handler, 0, "me:" + message).sendToTarget();
                            client.send(sendPacket);

                        } catch (SocketException e) {
                            e.printStackTrace();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }).start();

            }
        });

        new Thread(new Runnable() {
            @Override
            public void run() {
                DatagramSocket socket = null;
                try {
                    socket = new DatagramSocket(9999);
                    while (true) {

                        byte[] recBuffer = new byte[1024];
                        DatagramPacket recPacket = new DatagramPacket(recBuffer, recBuffer.length);
                        socket.receive(recPacket);
                        String message = new String(recPacket.getData(), 0, recPacket.getLength());
                        Message.obtain(handler, 1, "friends:" + message).sendToTarget();

                    }

                } catch (SocketException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }


            }
        }).start();

    }


    private String receive(DatagramSocket client) {
        try {

            byte[] buf = new byte[1024];
            DatagramPacket packet = new DatagramPacket(buf, buf.length);
            client.receive(packet);
            String receiveMessage = new String(packet.getData(), 0, packet.getLength());
            return receiveMessage;


        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    public static String getHostIp() {
        try {
            for (Enumeration<NetworkInterface> en = NetworkInterface
                    .getNetworkInterfaces(); en.hasMoreElements(); ) {
                NetworkInterface intf = en.nextElement();
                for (Enumeration<InetAddress> ipAddr = intf.getInetAddresses(); ipAddr
                        .hasMoreElements(); ) {
                    InetAddress inetAddress = ipAddr.nextElement();
                    if (!inetAddress.isLoopbackAddress() && !inetAddress.isLinkLocalAddress()) {
                        return inetAddress.getHostAddress().toString();
                    }
                }
            }
        } catch (SocketException ex) {
        } catch (Exception e) {
        }
        return null;
    }
}
